// pages/zhifu/zhifu.js
//获取应用实例
var app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isNeedLogistics: 1,
    yunPrice: 0,          //运费
    totalPrice: 0,
    coupons: [],
    hasNoCoupons: false,  //不使用优惠券为true ， 使用则false
    youhuijine: 0, //优惠券金额
    allGoodsAndYunPrice: 0,    //所有商品和运费价
    buyNowInfo: '',
    resourceUrl: app.globalData.apiUrl + '/public/uploads/goods/',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    
    //购买的商品
    wx.getStorage({
      key: "shopCarInfo",
      success: function (res) {
        console.log(res)
        that.setData({ buyNowInfo: res.data })
        //总价
        that.totalPrice()
        console.log(2222)
        console.log(that.data.buyNowInfo)
      }
    })
    //优惠劵
    that.coupons()

  },
  /**
   * 对应用户的优惠券
   */
  coupons: function () {
    var that = this
    wx.request({
      url: app.globalData.apiUrl + '/api/User/useCoupon',
      data: { openid: app.globalData.userInfo.open_id },
      method: 'GET',
      dataType: 'json',
      success: function (res) {
        console.log(res)
        that.setData({ coupons: res.data })
      },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    //默认地址
    that.defaultAddress()

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /**
   * 计算总价钱
   */
  totalPrice: function () {
    var that = this;
    //商品信息
    var buyNowInfo = that.data.buyNowInfo.goodsList
    var totalPrice = 0
    for (var i in buyNowInfo){
      totalPrice += buyNowInfo[i].price * buyNowInfo[i].num
    }
   
    that.setData({ totalPrice: totalPrice })
  },
  bindChangeCoupon: function (e) {
    var that = this
    var totalPrice = that.data.totalPrice
    var newPrice = totalPrice
    var value = e.detail.value//选择的优惠劵
    if (value != 0) {
      var index = value - 1
      var coupon = that.data.coupons[index]
      if (totalPrice < coupon.use_price) {

      } else {
        that.setData({ youhuijine: coupon.price })
      }
    } else {
      console.log('不使用优惠劵')
      that.setData({ totalPrice: newPrice, youhuijine: 0 })
    }
  },
  /**
   * 新增地址
   */
  addAddress: function () {

    wx.navigateTo({
      url: '../address_single/address_single',
    })
  },

  /**
   * 查找该用户的默认地址
   */
  defaultAddress: function () {
    var that = this
    wx.request({
      url: app.globalData.apiUrl + '/api/User/defaultAddress',
      data: { users_id: app.globalData.userInfo.id },
      method: 'GET',
      dataType: 'json',
      success: function (res) {
        console.log(res)
        that.setData({ defaultAddress: res.data })
      },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  /**
   * 提交订单
   */
  payOrder: function () {
    var that = this;
    wx.request({
      url: app.globalData.apiUrl + '/api/Pay/payfee',//改成你自己的链接
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data: { total_fee: that.data.totalPrice, openid: app.globalData.userInfo.open_id },
      method: 'POST',
      success: function (res) {
        console.log(res.data);
        console.log('调起支付');
        wx.requestPayment({
          'timeStamp': res.data.timeStamp,
          'nonceStr': res.data.nonceStr,
          'package': res.data.package,
          'signType': 'MD5',
          'paySign': res.data.paySign,
          'success': function (res) {
            console.log('success');
            that.createOrder()
            wx.showToast({
              title: '支付成功',
              icon: 'success',
              duration: 3000
            });
          },
          'fail': function (res) {
            console.log('fail');
          },
          'complete': function (res) {
            console.log('complete');
          }
        });
      },
      fail: function (res) {
        console.log(res.data)
      }
    });
  },
  /**
   * 创建订单
   */
  createOrder: function () {
    var that = this
    console.log(that.data.buyNowInfo)
    var userInfo = app.globalData.userInfo//用户信息
    var linkMan = that.data.defaultAddress.linkMan//收件人
    var mobile = that.data.defaultAddress.mobile//联系电话
    var address = that.data.defaultAddress.area + that.data.defaultAddress.address//地址
    wx.request({
      url: app.globalData.apiUrl + '/api/Pay/goodsOrder',
      data: { goodsList: that.data.buyNowInfo.goodsList, totalPrice: that.data.totalPrice, openid: userInfo.open_id, linkMan: linkMan, mobile: mobile, address: address},
      method: 'POST',
      dataType: 'json',
      success: function (res) {
        console.log(res)
      },
      fail: function (res) { },
      complete: function (res) { },
    })


  },
  /**
 * 删除地址
 */
  delAddress: function (tab) {
    var that = this
    //地址id
    var id = tab.currentTarget.dataset.id
    wx.request({
      url: app.globalData.apiUrl + '/api/User/delAddress',
      data: { id: id },
      method: 'POST',
      dataType: 'json',
      success: function (res) {
        if (res.data.status == 1) {
          that.defaultAddress()
        }
      },
      fail: function (res) { },
      complete: function (res) { },
    })

  }
})